package com.vf.admin.common.db.SqlUitls;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * 数据库ID生成工具类
 */
public class SequenceUtil {
	private static String currentTime = "0";
    private static String zero = "0000000";
    private static String currentZero = zero;
    private static String currentIndex = zero;
    private static Long currentCount = 0L;

    /**
     * 生成sequence
     *
     * @return String
     */
    public synchronized static String getSequence() {
        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");//设置日期格式
        String nowTime = df.format(new Date()).replace("-", "").replace(":", "").replace(" ", "");
        if (nowTime.equals(currentTime)) {
            if (Long.valueOf(currentZero.replace("0", "9")).equals(currentCount)) {
                currentIndex = currentIndex + "0";
                currentZero = currentZero + "0";
            }
            currentCount = currentCount + 1;
            currentIndex = currentIndex.substring(0, currentIndex.length() - currentCount.toString().length()) + currentCount;
        } else {
            currentCount = 0L;
            currentIndex = zero;
            currentZero = zero;
        }
        currentTime = nowTime;
        return currentTime + currentIndex;
    }

    /**
     * 测试生成的ID是否重复
     *
     * @param args
     */

    public static void main(String args[]) throws InterruptedException {
        Map map = new HashMap();
        for (int i = 0; i < 10000; i++) {
            String sequence = SequenceUtil.getSequence();
            map.put(sequence, sequence);
        }
       // System.out.println("生成的ID是否存在重复:" + ((map.size() == 10000) ? "无重复" : "存在重复"));
    }
}
